﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CF.Member.DAL.WeiboMember;
using CF.Tools.com.SinaSDK;
using System.Web.Script.Serialization;
using CF.Member.DAL.Member;
using CaifenWeb.UtilityCls;
using CaifenWeb.Models;

/* -------QQ 登录需用引用的命名空间----------------- */
using CF.Tools.com.QzoneSDK;
using CF.Tools.com.QzoneSDK.Context;

namespace CaifenWeb.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        /* 因为跨域名，所以session 失效，只能先保存静态变量做测试。*/
        //public static OutsideMemInfo meminfo = null;
        //public static SinaSerive sina = null;
        //public static QOpenClient qq = null;
         
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 网站登录入口
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        /// 微博第三方登录入口
        /// </summary>
        /// <returns></returns>
        public ActionResult WeiboLogin(string type,int isbind=0)
        {
             OutsideMemInfo meminfo = null;
            try
            {
                string url_ = Request.UrlReferrer.ToString();
                switch (type)
                {
                    case "sina":
                        meminfo = new OutsideMemInfo(url_, OutsideLoginType.sina, isbind);
                        Session["ThirdParty"] = meminfo;
                          SinaSerive sina = new SinaSerive();
                        sina = new SinaSerive();
                        Session["sinaweibo"] = sina;
                        sina.GetAuthorizationCode();
                        break;
                    case "qq":
                        meminfo = new OutsideMemInfo(url_, OutsideLoginType.qq, isbind);
                        Session["ThirdParty"] = meminfo;
                        QOpenClient qq = new QOpenClient();
                        qq = new QOpenClient();
                        Session["qqweibo"] = qq;
                        qq.GetAuthorizationCode();
                        break;
                    default:
                        return View("Index");
                }
            }
            catch {
                return RedirectToAction("index");
            }

            return View();
        }

        /// <summary>
        /// 第三方登录 授权回来函数
        /// </summary>
        /// <returns></returns>
        public ActionResult OutSideCallBack()
        {
            try
            {

                if ((Request.QueryString["oauth_verifier"] != null || Request.QueryString["code"] != null || Request.QueryString["oauth_vericode"] != null))   //  && Session["ThirdParty"] != null       //人人网返回参数是code
                {
                    OutsideMemInfo ThirdParty = (OutsideMemInfo)Session["ThirdParty"];
                    OutsideLoginType LoginType = ThirdParty.LoginType;
                    switch (LoginType)
                    {

                        case OutsideLoginType.sina:

                            SinaSerive oauth = (SinaSerive)Session["sinaweibo"];
                            string aaaaa = Request["code"].ToString();
                            oauth.GetAccessTokenByAuthorizationCode(Request["code"]);
                            Session["sinaweibo"] = oauth;
                            User userT = oauth.Users_Show();
                            string sex = userT.gender == "f" ? "女" : "男";
                            ThirdParty = new OutsideMemInfo(ThirdParty.RepathURL, LoginType, ThirdParty.IsBind, userT.id.ToString(), userT.screen_name, userT.avatar_large, sex,oauth.Token.access_token,int.Parse(oauth.Token.expires_in));
                            Session["ThirdParty"] = ThirdParty;
                            break;

                        case OutsideLoginType.qq:

                            QOpenClient qzone =(QOpenClient)Session["qqweibo"];
                            qzone.GetAccessTokenByAuthorizationCode(Request["code"]);
                            CF.Tools.com.QzoneSDK.Models.User currentUser = qzone.GetCurrentUser();
                            ThirdParty = new OutsideMemInfo(ThirdParty.RepathURL, LoginType, ThirdParty.IsBind,qzone.AccessToken.OpenId, currentUser.Nickname, currentUser.figureurl_2, currentUser.Gender,qzone.AccessToken.AccessToken,qzone.AccessToken.ExpiresAt);
                           
                            Session["ThirdParty"] = ThirdParty;
                        
                       //   CF.Tools.com.QzoneSDK.Models.QzoneBase a= qzone.AddTopic("苏老板准备请我吃饭，太开心了！");
                        //  CF.Tools.com.QzoneSDK.Models.QzoneBase aa = qzone.AddFeeds("苏老板呀苏老板!!!!!！", "http://www.51camel.com", "", "苏老板说请大家吃M记啦，大家鼓掌！", "http://www.51camel.com/Resources/BaseImage/logo.jpg", "", "", "", "");

                            break;
                        default:
                            throw new Exception();
                    }
                    //下面方法用在授权成功之后做的绑定或者新产生会员 用处。
                    if (!string.IsNullOrEmpty(ThirdParty.WeiBoUID))
                    {
                        int uid = 0;
                        int rcode = 0;
                        string rmsg = "";
                        FM_MemberDAL dal = new FM_MemberDAL();
                        dal.OutSideMemRelation(ThirdParty.WeiBoUID,ThirdParty.LoginType.ToString(), out uid, out rcode);
                        if (rcode == 1000)
                        {
                          
                            FM_MemberBindingDAL memBingDal=new FM_MemberBindingDAL();
                            memBingDal.CheckMemberBinding(uid, ThirdParty.WeiBoUID, ThirdParty.LoginType.ToString(), ThirdParty.AccessToken, ThirdParty.Expires_in);
                          
                            FormAuthenticationService authen = new FormAuthenticationService();
                            authen.SignIn(uid, true);
                            return Redirect(ThirdParty.RepathURL);
                        }
                        else
                        {
                            MemberModels models = new MemberModels();
                            models.memInfoObj = ThirdParty;
                            models.LoginType = ThirdParty.LoginType;
                            // return Redirect(ThirdParty.RepathURL);
                            return View(models);
                        }
                    }
                }

            }
            catch (Exception ex)
            {
               // Response.Write("授权失败，请联系网站客服:" + ex.Message + "_" + ex.StackTrace + "_" + ex.Source + "_" + ex.InnerException);
                return RedirectToAction("index");
            }
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(string bindUid,string bindType,string nickname,string sex)
        {
            try
            {
                FM_MemberDAL dal = new FM_MemberDAL();
                if (dal.CheckIsBinding(bindUid, bindType))
                {
                    return Json(new { rcode = -1000, rmsg = "帐号已经注册，请直接登录就可以啦！" });
                }
                if (dal.CheckNickName(nickname.Trim()))
                {
                    return Json(new { rcode = -1001, rmsg = "太遗憾了，昵称被人抢先一步注册了，换一个试下吧？" });
                }
                //接下来 昵称的正则验证。。
                int code = 0; string msg = "";
                DataStateValidator.NickNameCheck(nickname, out code, out msg);
                if(code!=1){
                    return Json(new { rcode = -1006, rmsg = msg });
                }

                OutsideMemInfo ThirdParty =(OutsideMemInfo)Session["ThirdParty"];
                //下面一定判断是否会绕过第三方登录请求过来。。
                if (string.IsNullOrEmpty(ThirdParty.WeiBoUID)) return Json(new { rcode = -1002, rmsg = "Sorry,你未通过微博或者QQ登录 验证你的信息，请重新授权！" });
                // 下面一定要判断是否属于第三方验证过来的注册用户，以免特殊人群搞窜值。
                if (ThirdParty.WeiBoUID != bindUid) return Json(new { rcode = -1003, rmsg = "Sorry,你的授权异常，请重新登录授权！" });
                //下面可以正常注册了。
                int uid = 0;
                bool flag = dal.AddMemberInfo(bindUid, bindType, nickname.Trim(), sex, out uid);
                if (flag)
                {
                    FM_MemberBindingDAL memBingDal = new FM_MemberBindingDAL();
                    memBingDal.AddMemberBinding(uid, ThirdParty.WeiBoUID, ThirdParty.LoginType.ToString(), ThirdParty.AccessToken, ThirdParty.Expires_in);

                    FormAuthenticationService authen = new FormAuthenticationService();
                    authen.SignIn(uid, false);
                    return Json(new { rcode = 1000, rmsg = "恭喜，注册成功！" });
                }
                else
                {
                    return Json(new { rcode = -1004, rmsg = "Sorry,注册失败" });
                }
            }
            catch(Exception ex)
            {
                return Json(new { rcode = -1005, rmsg = "注册失败异常:" + ex.Message });
            }
        }

        /// <summary>
        /// 新浪同步测试代码
        /// </summary>
        /// <returns></returns>
        public ActionResult test()
        {
            SinaSerive oauth = new SinaSerive();
            AccessToken aa = new AccessToken { access_token = "2.00LszFyBTY6vHCd13f17d6c5tLcqnB", expires_in = "86399", uid = 1804142475 };
            oauth.Token = aa;
            SinaUserAuthentication sinaObj = new SinaUserAuthentication(oauth);
            Dictionary<object, string> dateOut = sinaObj.GetUserInfo();
            int rcode=0;string rmsg="";
            sinaObj.ShareWeibo("大家好，我明天要修脖子。", out rcode, out rmsg);
            return Content("");
        }

        /// <summary>
        /// QQ同步测试代码
        /// </summary>
        /// <returns></returns>
        public ActionResult qqtest()
        {
            CF.Tools.com.QzoneSDK.Models.OAuthToken aa = new CF.Tools.com.QzoneSDK.Models.OAuthToken { AccessToken = "6B9F2FEB90990168B33CDEAFEC63AE54", ExpiresAt = 7776000, OpenId = "4A58CFF43711DEC8EEAF6731F8476BA6" };
            QOpenClient qzone = new QOpenClient(aa);
            CF.Tools.com.QzoneSDK.Models.User currentUser = qzone.GetCurrentUser();
            return Content("");
        }

        public JavaScriptResult qqqq()
        {
            //OutSideCallBack
          //  return Response.Write()
            return JavaScript("<script> window.location= '/home/OutSideCallBack'; </script>");
        }
    }
}
